package com.chookss.home.rank;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.adapter.NoticeListsAdapter;
import com.chookss.home.entity.NoticeListEntity;
import com.chookss.home.entity.StudyPlanEntiry;
import com.chookss.mine.MyOrderPagerAdapter;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.chookss.view.consecutivescroller.ConsecutiveViewPager;
import com.chookss.view.consecutivescroller.TabPagerAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class RankBaseFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvAccess)
    TextView tvAccess;
    @BindView(R.id.llAccess)
    LinearLayout llAccess;
    @BindView(R.id.tvUserNum)
    TextView tvUserNum;
    @BindView(R.id.llUsersNum)
    LinearLayout llUsersNum;
    @BindView(R.id.llTop)
    LinearLayout llTop;
    @BindView(R.id.title_back)
    LinearLayout title_back;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.tabLayout2)
    TabLayout tabLayout2;
    @BindView(R.id.viewPager)
    ConsecutiveViewPager viewPager;
    @BindView(R.id.viewPager2)
    ConsecutiveViewPager viewPager2;
    @BindView(R.id.consecutiveScrollerLayout)
    ConsecutiveScrollerLayout consecutiveScrollerLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private int type = 0; //0一级页面没有返回1是activity要返回
    private ArrayList<RankFragment> fragments = new ArrayList<>();
    private ArrayList<RankFragment2> fragments2 = new ArrayList<>();
    private TabPagerAdapter mAdapter;
    private TabPagerAdapter mAdapter2;
    private int choice = 0;//默认选择第一个

    public RankBaseFragment() {

    }

    public RankBaseFragment(int type) {
        this.type = type;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_rank, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    // 提供给Fragment获取使用。
    public SmartRefreshLayout getRefreshLayout() {
        return refreshLayout;
    }

    private void init() {
        //顶部状态栏 处理
        NavigationTools.saveUseRecord(mContext, "1", "15");
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            LinearLayout.LayoutParams topAllParams = (LinearLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            statusBar.setVisibility(View.VISIBLE);
            statusBar.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            title_back.setVisibility(View.GONE);
            tvTitle.getPaint().setFakeBoldText(true);
        } else {
            statusBar.setVisibility(View.GONE);
            title_back.setVisibility(View.VISIBLE);
        }
//        5 全部 1 每天（粉丝） 2 每周（会员） 4 每月（粉丝+会员） 0 （游客）
        fragments.add(new RankFragment(5));
        fragments.add(new RankFragment(1));
        fragments.add(new RankFragment(2));
        fragments.add(new RankFragment(4));
        mAdapter = new TabPagerAdapter(getChildFragmentManager(), getTabsAccess(), fragments);
        viewPager.setAdapter(mAdapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(3);
        llTop.post(new Runnable() {
            @Override
            public void run() {
                viewPager.setAdjustHeight(tabLayout.getHeight());
            }
        });
        fragments2.add(new RankFragment2(5));
        fragments2.add(new RankFragment2(0));
        fragments2.add(new RankFragment2(1));
        fragments2.add(new RankFragment2(2));
        mAdapter2 = new TabPagerAdapter(getChildFragmentManager(), getTabsUserNum(), fragments2);
        viewPager2.setAdapter(mAdapter2);
        tabLayout2.setupWithViewPager(viewPager2);
        viewPager2.setOffscreenPageLimit(3);
//        tabLayout2.post(new Runnable() {
//            @Override
//            public void run() {
//                viewPager2.setAdjustHeight(tabLayout2.getHeight());
//            }
//        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@androidx.annotation.NonNull RefreshLayout r) {
                // 把加载的动作传给当初的fragment
                if (choice == 0) {
                    fragments.get(viewPager.getCurrentItem()).onLoadMore(refreshLayout);
                } else {
                    fragments2.get(viewPager2.getCurrentItem()).onLoadMore(refreshLayout);
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout r) {

                if (choice == 0) {
                    fragments.get(viewPager.getCurrentItem()).onRefresh(refreshLayout);
                } else {
                    KLog.i(viewPager2.getCurrentItem());
                    fragments2.get(viewPager2.getCurrentItem()).onRefresh(refreshLayout);
                }

            }
        });
        refreshLayout.autoRefresh();
        llAccess.setSelected(true);
        llUsersNum.setSelected(false);
        getData();
    }

    private void getData() {
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.selectSuYuanNum, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        tvAccess.setText(jsonObject1.getString("visitNum") + "次");
                        tvUserNum.setText(jsonObject1.getString("empNum") + "人");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    @OnClick({R.id.title_back, R.id.title_link, R.id.llAccess, R.id.llUsersNum})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                if (mContext != null) {
                    mContext.finish();
                }
                break;
            case R.id.title_link:
                mContext.startActivity(new Intent(mContext,RankLinkActivity.class));
                break;
            case R.id.llAccess:
                choice = 0;
                llAccess.setSelected(true);
                llUsersNum.setSelected(false);
                tabLayout.setVisibility(View.VISIBLE);
                tabLayout2.setVisibility(View.GONE);
                viewPager.setVisibility(View.VISIBLE);
                viewPager2.setVisibility(View.GONE);
                break;
            case R.id.llUsersNum:
                choice = 1;
                llAccess.setSelected(false);
                llUsersNum.setSelected(true);
                tabLayout.setVisibility(View.GONE);
                tabLayout2.setVisibility(View.VISIBLE);
                viewPager.setVisibility(View.GONE);
                viewPager2.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }

    private List<String> getTabsAccess() {
        List<String> tabs = new ArrayList<>();
        tabs.add("全部");
        tabs.add("每天");
        tabs.add("每周");
        tabs.add("每月");
        return tabs;
    }

    private List<String> getTabsUserNum() {
        List<String> tabs = new ArrayList<>();
        tabs.add("全部");
        tabs.add("游客");
        tabs.add("粉丝");
        tabs.add("会员");
        return tabs;
    }

}
